/**
 * 
 */
package com.vector.ding.web.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.dao.bean.MenuEntity;
import com.vector.ding.dao.mybatis.mapper.MenuMapper;
import com.vector.ding.dao.mybatis.model.Menu;
import com.vector.ding.dao.mybatis.model.MenuExample;

/**
 * @author vector
 *
 */
@Service
public class MenuService {

	@Autowired
	private MenuMapper menuMapper;
	
	public List<MenuEntity> getMenuEntities(String parentMenuId) {
		List<Menu> menus = getMenus(parentMenuId);
		if (CollectionUtil.isEmpty(menus))
			return Collections.emptyList();
		
		List<MenuEntity> menuEntities = new ArrayList<MenuEntity>();
		for (Menu menu: menus) {
			MenuEntity menuEntity = new MenuEntity();
			menuEntity.setMenu(menu);
			List<MenuEntity> children = getMenuEntities(menu.getId());
			if (!CollectionUtil.isEmpty(children))
				menuEntity.setChildren(children);
			menuEntities.add(menuEntity);
		}
		 
		return menuEntities;
	}
	
	private List<Menu> getMenus(String parentMenuId) {
		MenuExample example = new MenuExample();
		if (StringUtil.isEmpty(parentMenuId)) {
			example.or().andParentIdEqualTo("");
			example.or().andParentIdIsNull();
		} else {
			example.createCriteria().andParentIdEqualTo(parentMenuId);
		}
		example.setOrderByClause("order_number asc");
		
		return menuMapper.selectByExample(example);
	}
}
